import 'dart:convert';

import 'package:example_example/pages/view/ItemToDoTaskView.dart';
import 'package:example_example/pages/view/LoadingDialog.dart';

import '../../../pages/view/LoadingView.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../../../global/Global.dart';
import '../../../global/GlobalUrl.dart';
import '../../../services/TLSizeFit.dart';
import '../../../util/HttpUtil.dart';
import '../../../util/LogUtil.dart';
import '../../../util/ToastUtils.dart';
import '../../../util/Storage.dart';
import '../../../pages/person/Login.dart';
import '../../view/ItemFinishTaskView.dart';
import '../../view/HeaderView.dart';
import '../../view/NoDataView.dart';
import '../../../util/TodoHttputil.dart';
import '../../../services/EventBus.dart';
import '../../../util/HttpMethod.dart';


/**刷新来自官网的demo
 * flutter_easyrefresh   刷新的第三方组件
 * https://pub.dev/packages/flutter_easyrefresh/example
 *
 * 办结任务
 *
 */

class PreparePage extends StatefulWidget {

  PreparePage({Key key}) : super(key: key);
  _PreparePageState createState() => _PreparePageState();

}

class _PreparePageState extends State<PreparePage> {

  EasyRefreshController _controller;

  // 条目总数
//  int _count = 6; //20

  List dataList = [];
  int pageIndex = 1;
  bool noDataflag = false;

  var eventBusRe;

  @override
  void initState() {
    super.initState();
    LogUtil.v("待办任务 售前立项。。。。initState");

    /**
     * 广播接收； H5审批成功后，刷新
     */
    eventBusRe =eventBus.on<ReFresshEvent>().listen((event) {
      print("2222收到了广播event:${event.reFreshFLag}");
      if(event.reFreshFLag =="2"){  // 去刷新数据
        print("222去刷新了");
        initHttpData();
      }
    });

    _controller = EasyRefreshController();

    HttpMethod.initDictionaryData(this.context);

    initHttpData();
  }

  @override
  Widget build(BuildContext context) {
    LogUtil.v("待办任务 售前立项。。。。build");
    return Scaffold(
//        appBar: AppBar(
//          title: Text("EasyRefresh"),
//        ),
      body: Stack(
        children: <Widget>[
          EasyRefresh.custom(
            enableControlFinishRefresh: false,
            // 是否开启控制结束刷新
            enableControlFinishLoad: true,
            // 是否开启控制结束加载
            controller: _controller,
            // EasyRefresh控制器
//          header: ClassicalHeader(),
            header: ClassicalHeader(
              enableInfiniteRefresh: false,
              refreshText: "拉动刷新",
              refreshReadyText: "释放刷新",
              refreshingText: "正在刷新...",
              refreshedText: "刷新完成",
              refreshFailedText: "刷新失败",
              noMoreText: "没有更多数据",
              showInfo: false, // 是否显示时间
//            infoText: "更新于 %T",
            ),
//          footer: ClassicalFooter(),
            footer: ClassicalFooter(
              loadText: "拉动加载",
              loadReadyText: "释放加载",
              loadingText: "正在加载...",
              loadedText: "加载完成",
              loadFailedText: "加载失败",
              noMoreText: "没有更多数据",
              infoText: "更新于 %T",
            ),
            onRefresh: () async {
              print('onRefresh');
              pageIndex = 1;
              initHttpData();
//          await Future.delayed(Duration(seconds: 2), () {
//
//          });
            },
            onLoad: () async {
              print('onLoad');
              pageIndex++;
              initHttpData();
//          await Future.delayed(Duration(seconds: 2), () {
//
////            _controller.finishLoad(noMore: _count >= 40);
//          });
            },
            slivers: <Widget>[
              SliverList(
                delegate: SliverChildBuilderDelegate(
                      (context, index) {
                    if (dataList != null && dataList.length > 0) {
                      return InkWell(
                        child: ItemToDoTaskView(context,dataList[index],index,"2"),
                        onTap: () {
                          showDialog(
                              context: context,
                              barrierDismissible: true,
                              builder: (_) {
                                return new LoadingDialog(text: "努力加载中");
                              });

                          setToDoNet(context,dataList[index],"2");
                        },
                      );
                    } else {
                      return Container(
                        height: TLSizeFit.screenHeight - TLSizeFit.setPx(200),
                        alignment: Alignment.center,
                        child: Center(
                          child: Text('还没有数据哦'),
                        ),
                        color: Colors.transparent,
                      );
                    }
                  },
//              childCount: dataList.length==0?1:dataList.length,
                  childCount: dataList.length,
                ),
              ),
            ],
          ),
          (this.dataList.length <= 0 && !noDataflag) ? LoadingView() : Container(),
          noDataflag ? NoDataView(): Container(),
        ],
      ),
    );
  }

  initHttpData() async {
//    http://10.66.1.100:8181/api/us-process/process/pageFinished?current=1&size=10

    String apiUrlhttp = GlobalUrl.PROCESSTASK;
    var map = {
      "processDefinitionKeys":"prepareProjectUpdateAuditProcess,prepareProjectAuditProcess",
      "current": pageIndex,
      "size": "10",
    };
    String access_token = await Storage.getToken();
    LogUtil.init(title: "来自LogUtil", isDebug: false, limitLength: 800);
    var mapHeaders = {
      Global.AUTHORIZATION: access_token,
      Global.CONTENT_TYPE: Global.APPLICATION_JSON
    };
    HttpUtil.get(apiUrlhttp, data: map, headers: mapHeaders, success: (data) {
      // 下拉刷新停止
      _controller.resetLoadState();
      //  上拉加载停止
      _controller.finishLoadCallBack();
//    _controller.finishLoad(noMore: false);
      _controller.finishLoad();

      var success = data["success"];
//      LogUtil.v("success:$success");
      var message = data["msg"];
      var body = data["data"];
      var code = data["code"];
//      LogUtil.v("body:$body");
      if (success != null && success == true) {
        LogUtil.v("进来了");
        List getList = body["records"];
//        LogUtil.v("getList:$getList");
        LogUtil.v("获取的接口数据：${getList.length}");

        if (pageIndex == 1) {
          dataList.clear();
          dataList.addAll(getList);
        } else {
          dataList.addAll(getList);
        }
        print(dataList.length);

        if (dataList.length == 0) {
          setState(() {
            noDataflag = true;
          });
        } else {
          setState(() {
            dataList = dataList;
            noDataflag = false;
          });
        }
      }
    }, error: (errorMsg) {
      print("待办任务..售前..errorMsg: $errorMsg");
      // 下拉刷新停止
      _controller.resetLoadState();

      //  上拉加载停止
      _controller.finishLoadCallBack();
//            _controller.finishLoad(noMore: false);
      _controller.finishLoad();
    });
  }
  @override
  void dispose() {
    super.dispose();
    _controller.dispose();

    //取消订阅
    eventBusRe.cancel();
  }

}
